package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"video/api/request"
	"video/internal/dao"
	"video/internal/model"
	"video/pkg"
)

func AddVideo(c *gin.Context) {
	var req request.AddVideo
	var videos model.Video

	if req.Image == "" || req.Video == "" || req.Title == "" || req.Info == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	file, err := c.FormFile(req.Image)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "接收失败",
			"data": nil,
		})
		return
	}

	uploadimage, err := pkg.Upload(file)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "上传失败",
			"data": nil,
		})
		return
	}

	formFile, err := c.FormFile(req.Video)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "接收失败",
			"data": nil,
		})
		return
	}

	uploadvideo, err := pkg.Upload(formFile)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "上传失败",
			"data": nil,
		})
		return
	}

	videos = model.Video{
		ImageUrl: uploadimage,
		VideoUrl: uploadvideo,
		Title:    req.Title,
		Info:     req.Info,
	}

	dao.AddFile(&videos)
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "视频发布成功",
		"data": videos,
	})

}

func ListVideo(c *gin.Context) {
	var videos []model.Video

	dao.GetListFile(&videos)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "列表展示功",
		"data": videos,
	})

}

func IncrLikeNumVideo(c *gin.Context) {
	var req request.IncrLikeNumVideo
	var videos model.Video

	if req.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	dao.GetOneByFile(&model.Video{Id: uint32(req.Id)}, &videos)

	if videos.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "视频不存在",
			"data": false,
		})
		return
	}

	videos.LikeNum += 1

	dao.UpdateFile(&videos)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "点赞成功",
		"data": true,
	})
}

func UpdateLikeNumVideo(c *gin.Context) {
	var req request.UpdateLikeNumVideo
	var videos model.Video

	if req.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	dao.GetOneByFile(&model.Video{Id: uint32(req.Id)}, &videos)

	if videos.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "视频不存在",
			"data": false,
		})
		return
	}

	videos.LikeNum -= 1

	dao.UpdateFile(&videos)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "取消点赞成功",
		"data": true,
	})
}
